<template>
  <div class="student-center">
    <!-- 查询区域 -->
    <el-row gutter="20" class="search-bar">
      <el-col :span="8">
        <el-input
            v-model="searchQuery"
            placeholder="按学员姓名查询"
            clearable
            size="small"
        ></el-input>
      </el-col>
      <el-col :span="16">
        <el-button type="primary" size="small" @click="fetchStudents(1)">
          查询
        </el-button>
        <el-button size="small" type="primary" @click="addStudent">新增学员</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
        <el-button
            v-if="hasUnverifiedStudents"
            size="small"
            type="success"
            @click="batchAudit"
        >
          批量审核
        </el-button>
        <el-upload
            class="upload-demo inline-upload"
            action="http://127.0.0.1:8081/manager-student/import"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
        >
          <el-button size="small" type="primary">批量导入学员</el-button>
        </el-upload>
      </el-col>
    </el-row>

    <!-- 学员列表 -->
    <el-table
        :data="students.records"
        border
        style="width: 100%; margin-top: 20px"
        v-if="students.records.length"
        :selection="selectedStudents"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" :selectable="selectable"></el-table-column>
      <el-table-column prop="stuName" label="学员姓名" width="180" />
      <el-table-column prop="fromPlace" label="籍贯" />
      <el-table-column prop="parentPhone" label="家长电话" width="180" />
      <el-table-column prop="currentGrade" label="年级" width="120" />
      <el-table-column prop="status" label="状态" width="120" />
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="mini" @click="editStudent(scope.row)">编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="deleteStudent(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-empty v-else description="暂无数据" style="margin: 20px 0" />

    <!-- 分页区域 -->
    <el-pagination
        v-if="students.total > 0"
        :current-page="students.current"
        :page-size="students.size"
        :total="students.total"
        layout="prev, pager, next"
        background
        style="text-align: center; margin-top: 20px"
        @current-change="fetchStudents"
    ></el-pagination>

    <!-- 新增学员的弹窗 -->
    <el-dialog
        v-model="addDialogVisible"
        title="新增学员"
        :before-close="closeDialog"
        width="50%"
    >
      <el-form :model="currentStudent" label-width="80px">
        <el-form-item label="学员姓名">
          <el-input v-model="currentStudent.stuName" />
        </el-form-item>
        <el-form-item label="籍贯">
          <el-input v-model="currentStudent.fromPlace" />
        </el-form-item>
        <el-form-item label="家长电话">
          <el-input v-model="currentStudent.parentPhone" />
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="currentStudent.currentGrade" />
        </el-form-item>
        <el-form-item label="是否首次参与活动">
          <el-select v-model="currentStudent.isFirst" placeholder="请选择">
            <el-option label="新生" value="1" />
            <el-option label="老生" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentStudent.status" placeholder="请选择状态">
            <el-option label="正常" value="正常" />
            <el-option label="异常" value="异常" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="currentStudent.comment" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveAddStudent">保存</el-button>
      </span>
    </el-dialog>

    <!-- 编辑学员的弹窗 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑学员"
        :before-close="closeDialog"
        width="50%"
    >
      <el-form :model="currentStudent" label-width="80px">
        <el-form-item label="学员姓名">
          <el-input v-model="currentStudent.stuName" />
        </el-form-item>
        <el-form-item label="登录ID">
          <el-input v-model="currentStudent.loginId" />
        </el-form-item>
        <el-form-item label="籍贯">
          <el-input v-model="currentStudent.fromPlace" />
        </el-form-item>
        <el-form-item label="家长电话">
          <el-input v-model="currentStudent.parentPhone" />
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="currentStudent.currentGrade" />
        </el-form-item>
        <el-form-item label="是否首次参与活动">
          <el-select v-model="currentStudent.isFirst" placeholder="请选择">
            <el-option label="新生" value="1" />
            <el-option label="老生" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentStudent.status" placeholder="请选择状态">
            <el-option label="正常" value="正常" />
            <el-option label="异常" value="异常" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="currentStudent.comment" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveStudent">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "StudentCenter",
  data() {
    return {
      searchQuery: "",  // 用于搜索学员
      students: {
        records: [],
        total: 0,
        size: 5,
        current: 1,
      },
      selectedStudents: [], // 选中的学生列表
      addDialogVisible: false,
      editDialogVisible: false,
      currentStudent: {
        id: null,
        loginId: null,
        stuName: "",
        fromPlace: "",
        parentPhone: "",
        currentGrade: "",
        isFirst: "",
        status: "",
        comment: ""
      },
      uploadHeaders: {
        Authorization: localStorage.getItem("token"),
      },
    };
  },
  computed: {
    hasUnverifiedStudents() {
      return this.students.records.some(student => student.status === "未审核");
    },
    selectable() {
      return (row) => row.status === "未审核";
    }
  },
  methods: {
    batchAudit() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning("请先选择需要审核的学员");
        return;
      }
      this.$confirm("确认批量审核所选学生吗?", "批量审核", {
        type: "warning",
      })
          .then(() => {
            const studentIds = this.selectedStudents.map((student) => student.id);
            this.$axios
                .post(
                    "/manager-student/batch-audit",
                    { studentIds },
                    { headers: { Authorization: localStorage.getItem("token") } }
                )
                .then(() => {
                  this.$message.success("批量审核成功");
                  this.fetchStudents(this.students.current);
                })
                .catch((error) => {
                  this.$message.error("批量审核失败");
                  console.error("批量审核失败", error);
                });
          })
          .catch(() => {
            this.$message.info("取消批量审核");
          });
    },
    handleSelectionChange(selectedRows) {
      this.selectedStudents = selectedRows;
    },
    fetchStudents(page = 1) {
      this.$axios
          .get("/manager-student/students", {
            params: {
              currentPage: page,
            },
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            const data = response.data.data;
            this.students = data;
          })
          .catch((error) => {
            console.error("获取学员数据失败", error);
          });
    },
    resetQuery() {
      this.searchQuery = "";
      this.fetchStudents(1);
    },
    editStudent(student) {
      this.currentStudent = { ...student };
      this.editDialogVisible = true;
    },
    addStudent() {
      this.addDialogVisible = true;
    },
    saveAddStudent() {
      const studentData = {
        id: this.currentStudent.id,
        stuName: this.currentStudent.stuName,
        status: this.currentStudent.status,
        fromPlace: this.currentStudent.fromPlace,
        parentPhone: this.currentStudent.parentPhone,
        currentGrade: this.currentStudent.currentGrade,
        isFirst: this.currentStudent.isFirst,
        comment: this.currentStudent.comment,
        loginId: this.currentStudent.loginId
      };
      this.$axios
          .post(`/manager-student/update`, studentData, {
            headers: {
              Authorization: localStorage.getItem("token"),
            }
          })
          .then((response) => {
            this.$message.success("学员信息更新成功");
            this.fetchStudents(this.students.current);
            this.closeAddDialog();
          })
          .catch((error) => {
            this.$message.error("更新学员信息失败");
            console.error("更新学员失败", error);
          });
    },
    saveStudent() {
      const studentData = {
        id: this.currentStudent.id,
        stuName: this.currentStudent.stuName,
        status: this.currentStudent.status,
        fromPlace: this.currentStudent.fromPlace,
        parentPhone: this.currentStudent.parentPhone,
        currentGrade: this.currentStudent.currentGrade,
        isFirst: this.currentStudent.isFirst,
        comment: this.currentStudent.comment,
        loginId: this.currentStudent.loginId
      };
      this.$axios
          .post(`/manager-student/update`, studentData, {
            headers: {
              Authorization: localStorage.getItem("token"),
            }
          })
          .then((response) => {
            this.$message.success("学员信息更新成功");
            this.fetchStudents(this.students.current);
            this.closeDialog();
          })
          .catch((error) => {
            this.$message.error("更新学员信息失败");
            console.error("更新学员失败", error);
          });
    },
    closeAddDialog() {
      this.addDialogVisible = false;
      this.currentStudent = {
        id: null,
        stuName: "",
        fromPlace: "",
        parentPhone: "",
        currentGrade: "",
        status: "",
      };
    },
    closeDialog() {
      this.editDialogVisible = false;
      this.currentStudent = {
        id: null,
        stuName: "",
        fromPlace: "",
        parentPhone: "",
        currentGrade: "",
        status: "",
      };
    },
    deleteStudent(studentId) {
      this.$confirm("确定删除该学员吗?", "删除学员", {
        type: "warning",
      })
          .then(() => {
            this.$axios
                .delete(`/manager-student/delete/${studentId}`, {
                  headers: {
                    Authorization: localStorage.getItem("token"),
                  }
                })
                .then((response) => {
                  this.$message.success("删除成功");
                  this.fetchStudents(this.students.current);
                })
                .catch((error) => {
                  this.$message.error("删除失败");
                  console.error("删除学员失败", error);
                });
          })
          .catch(() => {
            this.$message.info("取消删除");
          });
    },
    handleUploadSuccess(response) {
      if (response.code === 200) {
        this.$message.success("导入成功");
        this.fetchStudents(this.students.current);
      } else {
        this.$message.error(response.message);
      }
    },
    handleUploadError(error) {
      this.$message.error("导入失败");
      console.error("导入失败", error);
    },
  },
  mounted() {
    this.fetchStudents(1);
  },
};
</script>

<style scoped>
.student-center {
  padding: 20px;
  background-color: #f7f7f7;
}

.search-bar {
  margin-bottom: 20px;
}

.el-table {
  background-color: #fff;
}

.el-pagination {
  margin-top: 20px;
}

.inline-upload {
  display: inline-block;
  margin-left: 10px;
}
</style>